package com.feeyo.lib_baidutts.system;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;
import java.util.UUID;

/**
 * Created by Peripateticism on 2021/09/09
 * 方便实现，使用原生的语音相关
 */
final public class ChineseToSpeech {

    private TextToSpeech textToSpeech;
    public static boolean isSupportSpeech = true;//不支持文本朗读 启用录好的固定关键语音

    public ChineseToSpeech(Context context) {
        this.textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("TextToSpeech", "不支持朗读功能");
                        isSupportSpeech = false;
                    }
                }
            }
        });
    }

    public void speech(String text) {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        // 设置语速
        textToSpeech.setSpeechRate(1.0f);
        int status = textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        Log.e("原生播报状态", text + ";" + status);
    }

    public void speech(String text, PlayCallback listener) {
        String uuid = UUID.randomUUID().toString();
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        // 设置语速
        textToSpeech.setSpeechRate(1.0f);
        //TextToSpeech.QUEUE_FLUSH：该模式下在有新任务时候会清除当前语音任务，执行新的语音任务
        //TextToSpeech.QUEUE_ADD：该模式下会把新的语音任务放到语音任务之后
        int status = textToSpeech.speak(text, TextToSpeech.QUEUE_ADD,null,uuid);
        Log.e("原生播报状态", text + ";" + status);
        if (status == TextToSpeech.ERROR) {
            listener.success(status);
        }
    }


    public void destroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
    }
}